package com.example.sunmiv1.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.AddAllocationAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.entity.AllocationGoodsInfo;
import com.example.sunmiv1.entity.AllocationType;
import com.example.sunmiv1.entity.ChooseGoodInfo;
import com.example.sunmiv1.entity.StoreInfo;
import com.example.sunmiv1.entity.StoreListInfo;
import com.example.sunmiv1.entity.StoreRedeployment;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//  新增出庫單
public class AddAllocationActivity extends BaseActivity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.addDeposit_chooseFood)
    LinearLayout addDepositChooseFood;
    @BindView(R.id.addDepositSearch_edit)
    EditText addDepositSearchEdit;
    @BindView(R.id.addDepositSearch_code)
    ImageView addDepositSearchCode;
    @BindView(R.id.addDepositSearch_search)
    ImageView addDepositSearchSearch;
    @BindView(R.id.addDeposit_chooseStore)
    Spinner addDepositChooseStore;
    @BindView(R.id.addDeposit_storeLin)
    LinearLayout addDepositStoreLin;
    @BindView(R.id.addDeposit_remark)
    EditText addDepositRemark;
    @BindView(R.id.addDeposit_remarkLin)
    LinearLayout addDepositRemarkLin;
    @BindView(R.id.addDeposit_listView)
    ListView addDepositListView;
    @BindView(R.id.addDeposit_checkAll)
    TextView addDepositCheckAll;
    @BindView(R.id.addDeposit_submit)
    TextView addDepositSubmit;
    @BindView(R.id.addDeposit_complete)
    TextView addDepositComplete;
    @BindView(R.id.addDeposit_delete)
    TextView addDepositDelete;
    @BindView(R.id.addDeposit_operation)
    LinearLayout addDepositOperation;
    @BindView(R.id.spinner_allocation_type)
    Spinner spinnerAllocationType;
    @BindView(R.id.spinner_supplier)
    Spinner spinnerSupplier;
    @BindView(R.id.linear_supplier)
    LinearLayout linearSupplier;
    @BindView(R.id.linear_type)
    LinearLayout linearType;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;

    private Context context;
    private ACache aCache;
    private LoadingDialog loadingDialog;
    public static boolean opera = false;
    private AddAllocationAdapter addAllocationAdapter;
    private StoreListInfo storeListInfo;
    private int storeIndex = 0;
    private List<String> storeNameList = new ArrayList<>();
    private List<StoreListInfo.StoreListBean> storeList;
    private List<AllocationGoodsInfo.DataBean> list;

    private String userType;//用戶類型
    private String type = "";//出庫類型
    private String supplierId = "";//商戶供應商
    private String storeSupplierId = "";// 門店供應商
    private List<AllocationType.DataBean> typeList = new ArrayList<>();
    private List<StoreInfo.StoreSupplierBean> storeSupplierList = new ArrayList<>();//門店供應商
    private List<StoreInfo.SupplierBean> supplierList = new ArrayList<>();//商戶供應商
    private StoreInfo storeInfo;
    private List<StoreInfo.StoreListBean> storeListBeans = new ArrayList<>();//門店列表
    private StoreRedeployment storeRedeployment;
    private String order_number = "";//重新調撥訂單號
    private String stock_order_id = "";//重新調撥出庫單id
    private ArrayList<String> notInIdArr;// 已在此頁的貨物id

    private String alloOrOut;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    storeSupplierList.clear();
                    if ("2".equals(aCache.getAsString("userType"))) {
                        storeSupplierList.add(new StoreInfo.StoreSupplierBean("", "選擇供貨商"));
                    }
                    for (StoreInfo.StoreSupplierBean storeSupplierBean : storeInfo.getStoreSupplier()) {
                        storeSupplierList.add(storeSupplierBean);
                    }
                    if (storeSupplierList.size() > 0) {
                        List<String> arrayList = new ArrayList<>();

                        for (int i = 0; i < storeSupplierList.size(); i++) {
                            String name = storeSupplierList.get(i).getSupplier_name();
                            arrayList.add(name);
                        }

                        //往會員來源Spinner中添加數據
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, arrayList);  //創建一個數組適配器
                        adapter.setDropDownViewResource(R.layout.dropdown_stytle);
                        spinnerSupplier.setAdapter(adapter);

                    }
                    supplierList.clear();
                    if ("1".equals(aCache.getAsString("userType"))) {
                        supplierList.add(new StoreInfo.SupplierBean("", "選擇供貨商"));
                    }
                    for (StoreInfo.SupplierBean supplierBean : storeInfo.getSupplier()) {
                        supplierList.add(supplierBean);
                    }
                    if (supplierList.size() > 0) {
                        List<String> arrayList = new ArrayList<>();

                        for (int i = 0; i < supplierList.size(); i++) {
                            String name = supplierList.get(i).getSupplier_name();
                            arrayList.add(name);
                        }

                        //往會員來源Spinner中添加數據
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, arrayList);  //創建一個數組適配器
                        adapter.setDropDownViewResource(R.layout.dropdown_stytle);
                        spinnerSupplier.setAdapter(adapter);

                    }
                    storeListBeans.clear();
                    storeNameList.clear();
                    storeListBeans.add(new StoreInfo.StoreListBean("", "請選擇門店"));
                    storeNameList.add("請選擇門店");
                    for (StoreInfo.StoreListBean storeListBean : storeInfo.getStoreList()) {
                        storeNameList.add(storeListBean.getStoretag());
                        storeListBeans.add(storeListBean);
                    }
                    setSpinnerAdapter();
                    break;
                case 4:
                    list.clear();
                    for (StoreRedeployment.GoodsListBean goodsListBean : storeRedeployment.getGoodsList()) {
                        AllocationGoodsInfo.DataBean dataBean = new AllocationGoodsInfo.DataBean(goodsListBean);
                        list.add(dataBean);
                    }
                    setAddDepositAdapter();
                    order_number = storeRedeployment.getOrder_number();
                    stock_order_id = storeRedeployment.getTransfer_to_store_id();
                    break;
            }
        }
    };

    @Override
    protected void initView() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_add_deposit);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.addAllocation);
        context = this;
        aCache = ACache.get(context);
        userType = aCache.getAsString("userType");
        loadingDialog = new LoadingDialog(context);
        alloOrOut = getIntent().getStringExtra("AlloOrOut");
        if ("2".equals(userType)) {
            linearType.setVisibility(View.VISIBLE);
        } else {
            linearType.setVisibility(View.GONE);
        }
        if ("allo".equals(alloOrOut)) {
            addDepositRemarkLin.setVisibility(View.VISIBLE);
            linearType.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        notInIdArr = new ArrayList<>();
        list = new ArrayList<>();
        getAllocationType();
        getSupplier();
//        getStoreList();
        if (!TextUtils.isEmpty(getIntent().getStringExtra("id")) && !getIntent().getStringExtra("id").equals("0")) {
            getRedeployment();
        }
    }

    @Override
    protected void initListener() {
        //  選擇門店類型
        addDepositChooseStore.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                storeIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        /*選擇出庫類型*/
        spinnerAllocationType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                type = typeList.get(position).getId();
                if (type.equals("1") || type.equals("3")) {
                    linearSupplier.setVisibility(View.GONE);
                    if ("1".equals(aCache.getAsString("userType"))) {
                        if (type.equals("1") && list.size() > 0) {
                            addDepositStoreLin.setVisibility(View.VISIBLE);
                        } else {
                            addDepositStoreLin.setVisibility(View.GONE);
                        }
                    } else if ("2".equals(aCache.getAsString("userType"))) {
                        if (type.equals("3") && list.size() > 0) {
                            addDepositStoreLin.setVisibility(View.VISIBLE);
                        } else {
                            addDepositStoreLin.setVisibility(View.GONE);
                        }
                    }
                } else {
                    addDepositStoreLin.setVisibility(View.GONE);
                    if ("1".equals(aCache.getAsString("userType"))) {
                        if (type.equals("4") && list.size() > 0) {//4退貨出庫
                            linearSupplier.setVisibility(View.VISIBLE);
                        } else {
                            linearSupplier.setVisibility(View.GONE);
                        }
                    } else if ("2".equals(aCache.getAsString("userType"))) {
                        if (type.equals("9") && list.size() > 0) {//9向供貨商退貨出庫
                            linearSupplier.setVisibility(View.VISIBLE);
                        } else {
                            linearSupplier.setVisibility(View.GONE);
                        }
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        /*9向供貨商退貨出庫選擇供貨商*/
        spinnerSupplier.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (supplierList.size() > 0) {
                    supplierId = supplierList.get(position).getId();//商戶供應商
                }
                if (storeSupplierList.size() > 0) {
                    storeSupplierId = storeSupplierList.get(position).getId();//門店供應商
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }

    @OnClick({R.id.title_back, R.id.addDeposit_chooseFood, R.id.addDepositSearch_code, R.id.addDepositSearch_search, R.id.addDeposit_scanFood,
            R.id.addDeposit_checkAll, R.id.btn_to_top, R.id.addDeposit_submit, R.id.addDeposit_complete, R.id.addDeposit_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.btn_to_top:
                addDepositListView.setSelection(0);
                break;
            case R.id.addDeposit_chooseFood:
                Intent intent = new Intent(context, AllocationGoodsActivity.class);
                intent.putExtra("type", type);
                intent.putStringArrayListExtra("not_in_ids", notInIdArr);
                if ("2".equals(aCache.getAsString("userType"))) {
                    if (TextUtils.isEmpty(type)) {
                        Toast.makeText(context, "請選擇出庫類型", Toast.LENGTH_SHORT).show();
                    } else {
                        startActivityForResult(intent, 100);
                    }
                } else {
                    startActivityForResult(intent, 100);
                }
                break;
            case R.id.addDeposit_scanFood:
                if ("2".equals(aCache.getAsString("userType"))) {
                    if (TextUtils.isEmpty(type)) {
                        Toast.makeText(context, "請選擇出庫類型", Toast.LENGTH_SHORT).show();
                    } else {
                        aCache.put("addAllocationType", type);
                        scanGood(5, list);
                    }
                } else {
                    scanGood(5, list);
                }
                break;
            case R.id.addDepositSearch_code:
                startQrCode();
                break;
            case R.id.addDepositSearch_search:
                if (TextUtils.isEmpty(addDepositSearchEdit.getText().toString().trim())) {
                    Toast.makeText(context, "請輸入貨號/條碼/名稱", Toast.LENGTH_SHORT).show();
                    return;
                }
                String info = addDepositSearchEdit.getText().toString().trim();
                boolean flag = false;
                for (int i = 0; i < list.size(); i++) {
                    if (info.equals(list.get(i).getGoods_code())) {
                        flag = true;
                        addDepositListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        addDepositListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                addDepositListView.setSelection(finalI);
                            }
                        }, 800);
                        addAllocationAdapter.setSelect(i);
                        break;
                    }
                    if (info.equals(list.get(i).getSku_code())) {
                        flag = true;
                        addDepositListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        addDepositListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                addDepositListView.setSelection(finalI);
                            }
                        }, 800);
                        addAllocationAdapter.setSelect(i);
                        break;
                    }
                    if (info.equals(list.get(i).getGoods_number())) {
                        flag = true;
                        addDepositListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        addDepositListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                addDepositListView.setSelection(finalI);
                            }
                        }, 800);
                        addAllocationAdapter.setSelect(i);
                        break;
                    }
                    if (info.equals(list.get(i).getSku_goods_number())) {
                        flag = true;
                        addDepositListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        addDepositListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                addDepositListView.setSelection(finalI);
                            }
                        }, 800);
                        addAllocationAdapter.setSelect(i);
                        break;
                    }
                    if (info.equals(list.get(i).getGoods_name())) {
                        flag = true;
                        addDepositListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        addDepositListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                addDepositListView.setSelection(finalI);
                            }
                        }, 800);
                        addAllocationAdapter.setSelect(i);
                        break;
                    }
                }
                if (!flag) {
                    Toast.makeText(context, "已選商品中暫無此商品", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.addDeposit_checkAll:
                if (list.isEmpty()) {
                    Toast.makeText(this, "沒有可操作的數據", Toast.LENGTH_SHORT).show();
                    return;
                }
                opera = true;
                if (addDepositSubmit.getVisibility() == View.GONE) {
                    if ("全選".equals(addDepositCheckAll.getText().toString().trim())) {
                        for (AllocationGoodsInfo.DataBean dataBean : list) {
                            dataBean.setChecked(true);
                        }
                        addDepositCheckAll.setText(R.string.purRefundAdding_Choose_Item_Check_None);
                    } else {
                        for (AllocationGoodsInfo.DataBean dataBean : list) {
                            dataBean.setChecked(false);
                        }
                        addDepositCheckAll.setText(R.string.purRefundAdding_check_all);
                    }
                } else {
                    addDepositSubmit.setVisibility(View.GONE);
                    addDepositOperation.setVisibility(View.VISIBLE);
                    addDepositCheckAll.setText(R.string.purRefundAdding_check_all);
                }
                setAddDepositAdapter();
                break;
            case R.id.addDeposit_submit:
                if (list.size() == 0) {
                    Toast.makeText(context, "請先選擇商品", Toast.LENGTH_SHORT).show();
                    return;
                }
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getStock_price() == 0) {
                        Toast.makeText(context, "請先設置" + list.get(i).getGoods_name() + "的出庫價", Toast.LENGTH_SHORT).show();
                        addDepositListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        addDepositListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                addDepositListView.setSelection(finalI);
                            }
                        }, 800);
                        addAllocationAdapter.setSelect(i);
                        return;
                    }
                    if (TextUtils.isEmpty(list.get(i).getOutput_num())) {
                        Toast.makeText(context, "請先設置" + list.get(i).getGoods_name() + "的調撥數量", Toast.LENGTH_SHORT).show();
                        addDepositListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        addDepositListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                addDepositListView.setSelection(finalI);
                            }
                        }, 800);
                        addAllocationAdapter.setSelect(i);
                        return;
                    }
                }
                if (TextUtils.isEmpty(type)) {
                    Toast.makeText(context, "請選擇出庫類型", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("1".equals(aCache.getAsString("userType"))) {
                    if (type.equals("1") && 0 == storeIndex) {
                        Toast.makeText(context, "請選擇門店", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (type.equals("4") && TextUtils.isEmpty(supplierId)) {
                        Toast.makeText(context, "請選擇供貨商", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else if ("2".equals(aCache.getAsString("userType"))) {
                    if (type.equals("3") && 0 == storeIndex) {
                        Toast.makeText(context, "請選擇門店", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (type.equals("9") && TextUtils.isEmpty(storeSupplierId)) {
                        Toast.makeText(context, "請選擇供貨商", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                new AlertDialog.Builder(this).setTitle("出庫操作")//設置對話框標題
                        .setMessage("確定要出庫？")//設置顯示的內容
                        .setPositiveButton("確定", (dialog, which) -> {
                            AllocateConfirm();
                        })
                        .setNegativeButton("取消", (dialog, which) -> {
                                }
                        ).show();//顯示此對話框
                break;
            case R.id.addDeposit_complete:
                opera = false;
                addDepositSubmit.setVisibility(View.VISIBLE);
                addDepositOperation.setVisibility(View.GONE);
                addDepositCheckAll.setText(R.string.operation);
                setAddDepositAdapter();
                break;
            case R.id.addDeposit_delete:
                for (int i = list.size() - 1; i >= 0; i--) {
                    if (list.get(i).isChecked()) {
                        notInIdArr.remove(list.get(i).getId());
                        list.remove(i);
                    }
                }
                setAddDepositAdapter();
                if (list.isEmpty()) {
                    linearType.setVisibility(View.GONE);
                    addDepositRemarkLin.setVisibility(View.GONE);
                }
                break;
        }
    }

    private void setAddDepositAdapter() {
        if (addAllocationAdapter == null) {
            addAllocationAdapter = new AddAllocationAdapter(context, list);
            addDepositListView.setAdapter(addAllocationAdapter);
        } else {
            addAllocationAdapter.notifyDataSetChanged();
        }
        addAllocationAdapter.setChoose(index -> {
            Intent intent = new Intent(context, StringCodeOperationActivity.class);
            intent.putExtra("operation", 14);
            intent.putExtra("good", list.get(index));
            startActivityForResult(intent, 200);
        });
    }

    private void setSpinnerAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_drop, storeNameList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drops);
        addDepositChooseStore.setAdapter(arrayAdapter);
        arrayAdapter.notifyDataSetChanged();
    }

    /*獲取出庫類型0其他出庫   1向商戶退貨出庫  2盤虧出庫  3調撥出庫 4 退貨出庫  9向供貨商退貨出庫*/
    private void getAllocationType() {
        typeList.clear();
        typeList.add(new AllocationType.DataBean("", "出庫類型"));
        typeList.add(new AllocationType.DataBean("0", "其他出庫"));
        if ("1".equals(aCache.getAsString("userType"))) {
            typeList.add(new AllocationType.DataBean("1", "調撥出庫"));// 有門店選擇
            typeList.add(new AllocationType.DataBean("4", "退貨出庫"));// 有供貨商選擇
        } else if ("2".equals(aCache.getAsString("userType"))) {
            typeList.add(new AllocationType.DataBean("1", "向商戶退貨出庫"));
            typeList.add(new AllocationType.DataBean("3", "調撥出庫"));// 有門店選擇
            typeList.add(new AllocationType.DataBean("9", "向供貨商退貨出庫"));// 有供貨商選擇
        }


        if (typeList.size() > 0) {
            List<String> arrayList = new ArrayList<>();

            for (int i = 0; i < typeList.size(); i++) {
                String name = typeList.get(i).getType();
                arrayList.add(name);
            }

            //往會員來源Spinner中添加數據
            ArrayAdapter<String> adapter = new ArrayAdapter<>(context, R.layout.spinner_item, arrayList);  //創建一個數組適配器
            adapter.setDropDownViewResource(R.layout.dropdown_stytle);
            spinnerAllocationType.setAdapter(adapter);

        }
    }


    /*獲取供應商（在type爲"9"的時候“向供貨商退貨出庫”*/
    private void getSupplier() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("user_type", aCache.getAsString("userType"));
            HttpUtils.post(context, Common.STORE_SUPPLIER, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    Gson gson = new Gson();
                    storeInfo = GsonUtils.JsonToBean(text, StoreInfo.class);
                    Message msg = new Message();
                    if (storeInfo.getStatus() == 1) {
                        msg.what = 3;
                    } else {

                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /*重新調撥*/
    private void getRedeployment() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("stock_order_id", getIntent().getStringExtra("id"));
            HttpUtils.post(context, Common.STORE_REDEPLOYMENT, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    Gson gson = new Gson();
                    storeRedeployment = GsonUtils.JsonToBean(text, StoreRedeployment.class);
                    Message msg = new Message();
                    if (storeRedeployment.getStatus() == 1) {
                        msg.what = 4;
                    } else {

                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /*提交出庫*/
    private void AllocateConfirm() {
        loadingDialog.show();
        String url = "";
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("stock_order_id", stock_order_id);//門店調撥出庫商戶拒絕後重新調撥的出庫單id
            jsonObject.put("order_number", order_number);//原出庫單訂單號,用於重新調撥提交傳的參數
            jsonObject.put("goodsList", new Gson().toJson(list));
            jsonObject.put("user_type", aCache.getAsString("userType"));
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("remarks", addDepositRemark.getText().toString().trim());

            if (typeList.size() == 1) {
                jsonObject.put("type", "1");
            } else {
                jsonObject.put("type", type);
            }
            if ("1".equals(aCache.getAsString("userType"))) {// 商戶出庫操作   ->storeid
                url = Common.ALLOCATE_CONFIRM;
                if (type.equals("1")) {
                    jsonObject.put("store_id", storeListBeans.get(storeIndex).getId());//目標門店id
                } else {
                    jsonObject.put("store_id", "");//目標門店id
                }
                if (type.equals("4")) {
                    jsonObject.put("supplier_id", supplierId);
                } else {
                    jsonObject.put("supplier_id", "");
                }
//                jsonObject.put("store_id", storeSupplierId);
                jsonObject.put("storeid", aCache.getAsString("storeid"));
            } else if ("2".equals(aCache.getAsString("userType"))) { // 門店出庫操作   storeid->transfer_id
                url = Common.STORE_ALLOCATION_OPERATION;
                jsonObject.put("storeid", aCache.getAsString("storeid"));
                if (type.equals("3")) {
                    jsonObject.put("transfer_id", storeListBeans.get(storeIndex).getId());//目標門店id
                } else {
                    jsonObject.put("transfer_id", "");//目標門店id
                }
                if (type.equals("9")) {
                    jsonObject.put("supplier_id", storeSupplierId);
                } else {
                    jsonObject.put("supplier_id", "");
                }
            }
            LogUtil.i("商戶供應商：" + supplierId);
            LogUtil.i("門店供應商：" + storeSupplierId);
            LogUtil.i("門店：" + storeListBeans.get(storeIndex).getId());
            HttpUtils.post(context, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            list.clear();
                            notInIdArr.clear();
                            setAddDepositAdapter();
                            addDepositRemark.setText("");
                            addDepositStoreLin.setVisibility(View.GONE);
                            addDepositRemarkLin.setVisibility(View.GONE);
                            order_number = "";
                            stock_order_id = "";
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*// 開始掃碼
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
        Intent intent = new Intent(context, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }
*/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
        //Log.e(TAG, "onActivityResult: " + data);
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case Constant.REQ_QR_CODE:
                    Bundle bundle = data.getExtras();
                    addDepositSearchEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
                    String info = addDepositSearchEdit.getText().toString().trim();
                    boolean flag = false;
                    if ("2".equals(aCache.getAsString("userType")) && type.equals("1") && list.size() > 0) {
                        typeList.clear();
                        typeList.add(new AllocationType.DataBean("1", "向商戶退貨出庫"));
                        if (typeList.size() > 0) {
                            List<String> arrayList = new ArrayList<>();
                            for (int i = 0; i < typeList.size(); i++) {
                                String name = typeList.get(i).getType();
                                arrayList.add(name);
                            }

                            //往會員來源Spinner中添加數據
                            ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, arrayList);  //創建一個數組適配器
                            adapter.setDropDownViewResource(R.layout.dropdown_stytle);
                            spinnerAllocationType.setAdapter(adapter);

                        }
                    } /*else {
                        getAllocationType();
                    }*/
                    for (int i = 0; i < list.size(); i++) {
                        if (info.equals(list.get(i).getGoods_code())) {
                            flag = true;
                            addDepositListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            addDepositListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    addDepositListView.setSelection(finalI);
                                }
                            }, 800);
                            addAllocationAdapter.setSelect(i);
                            break;
                        }
                        if (info.equals(list.get(i).getSku_code())) {
                            flag = true;
                            addDepositListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            addDepositListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    addDepositListView.setSelection(finalI);
                                }
                            }, 800);
                            addAllocationAdapter.setSelect(i);
                            break;
                        }
                        if (info.equals(list.get(i).getGoods_number())) {
                            flag = true;
                            addDepositListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            addDepositListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    addDepositListView.setSelection(finalI);
                                }
                            }, 800);
                            addAllocationAdapter.setSelect(i);
                            break;
                        }
                        if (info.equals(list.get(i).getSku_goods_number())) {
                            flag = true;
                            addDepositListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            addDepositListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    addDepositListView.setSelection(finalI);
                                }
                            }, 800);
                            addAllocationAdapter.setSelect(i);
                            break;
                        }
                    }
                    if (!flag) {
                        Toast.makeText(context, "已選商品中暫無此商品", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 100://選擇商品返回的數據
                    linearType.setVisibility(View.VISIBLE);
                    addDepositRemarkLin.setVisibility(View.VISIBLE);
                    list.addAll((List<AllocationGoodsInfo.DataBean>) data.getSerializableExtra("choice_list"));
                    for (AllocationGoodsInfo.DataBean dataBean : list) {
                        dataBean.setChecked(false);
                        notInIdArr.add(dataBean.getId());
                        LogUtil.i("backlist.stockPrice:" + dataBean.getStock_price());
                        LogUtil.i("backlist.Output_num:" + dataBean.getOutput_num());
                    }
                    LogUtil.i("backList.size():" + list.size() + "list.size():" + list.size());
                    if ("2".equals(aCache.getAsString("userType")) && type.equals("1") && list.size() > 0) {
                        typeList.clear();
                        typeList.add(new AllocationType.DataBean("1", "向商戶退貨出庫"));
                        if (typeList.size() > 0) {
                            List<String> arrayList = new ArrayList<>();

                            for (int i = 0; i < typeList.size(); i++) {
                                String name = typeList.get(i).getType();
                                arrayList.add(name);
                            }

                            //往會員來源Spinner中添加數據
                            ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, arrayList);  //創建一個數組適配器
                            adapter.setDropDownViewResource(R.layout.dropdown_stytle);
                            spinnerAllocationType.setAdapter(adapter);

                        }
                    }
                    if (list.size() > 0) {
                        linearType.setVisibility(View.VISIBLE);
                        if ("1".equals(aCache.getAsString("userType"))) {
                            //調撥出庫
                            if (type.equals("1")) {
                                addDepositStoreLin.setVisibility(View.VISIBLE);
                            } else {
                                addDepositStoreLin.setVisibility(View.GONE);
                                //退貨出庫
                                if (type.equals("4")) {
                                    linearSupplier.setVisibility(View.VISIBLE);
                                } else {
                                    linearSupplier.setVisibility(View.GONE);
                                }
                            }
                        } else if ("2".equals(aCache.getAsString("userType"))) {
                            //調撥出庫
                            if (type.equals("3")) {
                                addDepositStoreLin.setVisibility(View.VISIBLE);
                            } else {
                                addDepositStoreLin.setVisibility(View.GONE);
                                //向供貨商退貨出庫
                                if (type.equals("9")) {
                                    linearSupplier.setVisibility(View.VISIBLE);
                                } else {
                                    linearSupplier.setVisibility(View.GONE);
                                }
                            }
                        }
                        addDepositRemarkLin.setVisibility(View.VISIBLE);
                    } else {
                        addDepositStoreLin.setVisibility(View.GONE);
                        linearSupplier.setVisibility(View.GONE);
                        addDepositRemarkLin.setVisibility(View.GONE);
                    }
                    setAddDepositAdapter();
                    break;
                case 110://選擇商品返回的數據
                    linearType.setVisibility(View.VISIBLE);
                    addDepositRemarkLin.setVisibility(View.VISIBLE);
                    list.clear();
                    list.addAll((List<AllocationGoodsInfo.DataBean>) data.getSerializableExtra("list"));
                    for (AllocationGoodsInfo.DataBean dataBean : list) {
                        dataBean.setChecked(false);
                        notInIdArr.add(dataBean.getId());
                    }
                    LogUtil.i("backList.size():" + list.size() + "list.size():" + list.size());
                    if ("2".equals(aCache.getAsString("userType")) && type.equals("1") && list.size() > 0) {
                        typeList.clear();
                        typeList.add(new AllocationType.DataBean("1", "向商戶退貨出庫"));
                        if (typeList.size() > 0) {
                            List<String> arrayList = new ArrayList<>();

                            for (int i = 0; i < typeList.size(); i++) {
                                String name = typeList.get(i).getType();
                                arrayList.add(name);
                            }

                            //往會員來源Spinner中添加數據
                            ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, arrayList);  //創建一個數組適配器
                            adapter.setDropDownViewResource(R.layout.dropdown_stytle);
                            spinnerAllocationType.setAdapter(adapter);

                        }
                    }
                    if (list.size() > 0) {
                        linearType.setVisibility(View.VISIBLE);
                        if ("1".equals(aCache.getAsString("userType"))) {
                            //調撥出庫
                            if (type.equals("1")) {
                                addDepositStoreLin.setVisibility(View.VISIBLE);
                            } else {
                                addDepositStoreLin.setVisibility(View.GONE);
                                //退貨出庫
                                if (type.equals("4")) {
                                    linearSupplier.setVisibility(View.VISIBLE);
                                } else {
                                    linearSupplier.setVisibility(View.GONE);
                                }
                            }
                        } else if ("2".equals(aCache.getAsString("userType"))) {
                            //調撥出庫
                            if (type.equals("3")) {
                                addDepositStoreLin.setVisibility(View.VISIBLE);
                            } else {
                                addDepositStoreLin.setVisibility(View.GONE);
                                //向供貨商退貨出庫
                                if (type.equals("9")) {
                                    linearSupplier.setVisibility(View.VISIBLE);
                                } else {
                                    linearSupplier.setVisibility(View.GONE);
                                }
                            }
                        }
                        addDepositRemarkLin.setVisibility(View.VISIBLE);
                    } else {
                        addDepositStoreLin.setVisibility(View.GONE);
                        linearSupplier.setVisibility(View.GONE);
                        addDepositRemarkLin.setVisibility(View.GONE);
                    }
                    setAddDepositAdapter();
                    break;
                case 200:
                    AllocationGoodsInfo.DataBean bean = (AllocationGoodsInfo.DataBean) data.getSerializableExtra("bean");
                    int index = 0;
                    for (int t = 0; t < list.size(); t++) {
                        if (bean.getGoods_id().equals(list.get(t).getGoods_id())) {
                            if ("2".equals(bean.getAttribute_state())) {
                                if (bean.getSku_id().equals(list.get(t).getSku_id())) {
                                    index = t;
                                    break;
                                }
                            } else {
                                index = t;
                                break;
                            }
                        }
                    }
                    list.set(index, bean);
                    setAddDepositAdapter();
                    break;
            }
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否則所有的組件都不會有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);

    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //獲取輸入框當前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 點擊的是輸入框區域，保留點擊EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
